package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.BuyTogetherUser;
import com.rongke.model.Sku;
import com.rongke.redis.CacheUtil;
import com.rongke.service.BuyTogetherUserService;
import com.rongke.service.MuserService;
import com.rongke.service.OrdersService;
import com.rongke.service.SkuService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @BuyTogetherUserController
 * @Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/buyTogetherUser")
@Transactional
@CrossOrigin
public class BuyTogetherUserController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private BuyTogetherUserService buyTogetherUserService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private SkuService skuService;
    @Autowired
    private MuserService muserService;
    @Autowired
    private OrdersService ordersService;
    /**
     * @添加
     * @param buyTogetherUser
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addBuyTogetherUser(@RequestBody BuyTogetherUser buyTogetherUser){
        log.debug("添加");
        buyTogetherUserService.insert(buyTogetherUser);
        return JsonResp.ok(buyTogetherUser);
    }

    /**
     * @修改
     * @param buyTogetherUser
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateBuyTogetherUser(@RequestBody BuyTogetherUser buyTogetherUser){
        log.debug("修改");
        buyTogetherUserService.updateById(buyTogetherUser);
        return JsonResp.ok(buyTogetherUser);
    }
    /**
     * @根据id查找
     * @param btgId 拼团商品表id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectBuyTogetherUser(Long btgId){
        log.debug("查找");
        EntityWrapper<BuyTogetherUser> ew=new EntityWrapper<>();
        ew.eq("btg_id",btgId);
        BuyTogetherUser buyTogetherUser = buyTogetherUserService.selectOne(ew);

        return JsonResp.ok(buyTogetherUser);
    }

    /**
     * @获取某个商品已开团的列表
     * @param goodsId 商品id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectBuyTogetherUserList", method = RequestMethod.GET)
    public JsonResp selectBuyTogetherUserList(Long goodsId, Page page){
        log.debug("获取某个商品已开团的列表");
        Map map=new HashMap();
        map.put("goodsId",goodsId);
        map.put("isActivityOn",1);
        map.put("startIndex",(page.getCurrent()-1)*page.getSize());
        map.put("size",page.getCurrent());
//        List<BuyTogetherUser> buyTogetherUsers1 = buyTogetherUserService.selectBuyTogetherUser(map);
        List<BuyTogetherUser> buyTogetherUserList=buyTogetherUserService.selectBuyTogetherUserPage(map);
        List<Map> dataMaps=new ArrayList<>();
        for(int i=0,y=buyTogetherUserList.size();i<y;i++){
            Map dataMap=new HashMap();
            BuyTogetherUser btu=buyTogetherUserList.get(i);
            dataMap.put("avatarUrl",btu.getMuser().getAvatarUrl());
            dataMap.put("userName",btu.getMuser().getUserName());
            //开团时间
            Date startTime=btu.getBuyTogetherTime();
            Long leftTime = startTime.getTime()+btu.getBtg().getBuyTogetherLimitTime()*60*60*1000-new Date().getTime();
            dataMap.put("leftTime",leftTime);
            dataMap.put("buyTogetherCode",btu.getBuyTogetherCode());
            dataMap.put("leftNum",btu.getBtg().getNeedTogetherNum()-btu.getNowTogetherNum());
            dataMaps.add(dataMap);
        }
        Integer size= buyTogetherUserService.selectBuyTogetherUserPageSize(map);
        page.setRecords(dataMaps);
        page.setTotal(size);
        return JsonResp.ok(page);
    }

    /**
     * @我的拼团列表
     * @param token 会员令牌
     * @param status 1待成团2拼团成功3拼团失败
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/myBuyTogetherList", method = RequestMethod.GET)
    public JsonResp myBuyTogetherList(String token,String status,Page page){
        log.debug("我的拼团列表");
        if(!cacheUtil.hasKey(token)){
            return JsonResp.fa(muserService.LOGINSTR);
        }
        String userId=cacheUtil.get(token);
        Map map=new HashMap();
        map.put("muserId",userId);
        if(status!=null){
            map.put("status",status);
        }
        map.put("startIndex",(page.getCurrent()-1)*page.getSize());
        map.put("size",page.getSize());
        List<Map> ordersList=ordersService.selectBuyTogehterList(map);
        Integer size=ordersService.selectBuyTogehterListSize(map);
        page.setRecords(ordersList);
        page.setTotal(size);
        return JsonResp.ok(page);
    }


    /**
     * @获取某个商品已开团详情
     * @param buyTogetherCode 开团号
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectBuyTogetherGoodsDetail", method = RequestMethod.GET)
    public JsonResp selectBuyTogetherGoodsDetail(String buyTogetherCode){
        log.debug("获取某个商品已开团详情");
        Map map=new HashMap();
        map.put("isActivityOn",1);
        map.put("buyTogetherCode",buyTogetherCode);
        List<BuyTogetherUser> buyTogetherUsers = buyTogetherUserService.selectBuyTogetherUser(map);
        Map dataMap=new HashMap();
        dataMap.put("buyTogetherGoods",buyTogetherUsers.get(0).getBtg());
        List<Map> maps=new ArrayList<>();
        for(int i=0,y=buyTogetherUsers.size();i<y;i++){
            Map map1=new HashMap();
            BuyTogetherUser buyTogetherUser=buyTogetherUsers.get(i);
            map1.put("userName",buyTogetherUser.getMuser().getUserName());
            map1.put("avatarUrl",buyTogetherUser.getMuser().getAvatarUrl());
            map1.put("isHead",buyTogetherUser.getHead());
            map1.put("buyTogetherTime",buyTogetherUser.getBuyTogetherTime());
            maps.add(map1);
        }
        //开团时间
        Date startTime=buyTogetherUsers.get(0).getBuyTogetherTime();
        Long leftTime = startTime.getTime()+buyTogetherUsers.get(0).getBtg().getBuyTogetherLimitTime()*60*60*1000-new Date().getTime();
        Long endTime=startTime.getTime()+buyTogetherUsers.get(0).getBtg().getBuyTogetherLimitTime()*60*60*1000;
        dataMap.put("userDataList",maps);
        dataMap.put("leftTime", leftTime);
        dataMap.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime));
        return JsonResp.ok(dataMap);
    }


    /**
     * @根据条件查找
     * @param buyTogetherUser
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectBuyTogetherUserByCondition(@RequestBody BuyTogetherUser buyTogetherUser){
        log.debug("根据条件查找");
        if(buyTogetherUser==null)
            return JsonResp.toFail("参数不能为空");
        List<BuyTogetherUser> buyTogetherUserList=buyTogetherUserService.selectByCondition(buyTogetherUser);
        return JsonResp.ok(buyTogetherUserList);
    }

    /**
     * @判断是否已参加某个拼团活动
     * @param token  令牌
     * @param  buyTogetherCode 拼团号
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/canbuyTogetherUser", method = RequestMethod.GET)
    public JsonResp canbuyTogetherUser(String token,String buyTogetherCode){
        log.debug("判断是否已参加某个拼团活动");
       if(!cacheUtil.hasKey(token)){
           return JsonResp.fa(muserService.LOGINSTR);
       }
       String muserId=cacheUtil.get(token);
       EntityWrapper<BuyTogetherUser> ew=new EntityWrapper<>();
        ew.eq("muser_id",muserId);
        ew.eq("buy_together_code",buyTogetherCode);
        BuyTogetherUser btu=buyTogetherUserService.selectOne(ew);
        if(btu!=null){
            return JsonResp.fa("您已经参加过该团活动");
        }
        return JsonResp.ok();
    }




    /**
     * @拼团成功
     * @param buyTogetherCode  开团号
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/buyTogetherSuccess", method = RequestMethod.GET)
    public JsonResp buyTogetherSuccess(String buyTogetherCode,Long userId){
        log.debug("拼团成功");
        Map map=new HashMap();
//        map.put("isActivityOn",1);
        map.put("status","1,2");
        map.put("buyTogetherCode",buyTogetherCode);
        List<BuyTogetherUser> buyTogetherUsers = buyTogetherUserService.selectBuyTogetherUser(map);
        List<Map> maps=new ArrayList<>();
        Date buyTogetherTime=null;
        int i=0,y=buyTogetherUsers.size();
        for(;i<y;i++){
            Map map1=new HashMap();
            BuyTogetherUser buyTogetherUser=buyTogetherUsers.get(i);
            if(userId.equals(buyTogetherUser.getMuserId())){
                buyTogetherTime=buyTogetherUser.getBuyTogetherTime();
            }
            map1.put("avatarUrl",buyTogetherUser.getMuser().getAvatarUrl());
            map1.put("isHead",buyTogetherUser.getHead());
            map1.put("buyTogetherTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(buyTogetherUser.getBuyTogetherTime()));
            map1.put("buyTogetherCode",buyTogetherUser.getBuyTogetherCode());
            map1.put("userName",buyTogetherUser.getMuser().getUserName());
            maps.add(map1);
        }
        //开团时间
        Date startTime=buyTogetherUsers.get(0).getBuyTogetherTime();
        Long leftTime = startTime.getTime()+buyTogetherUsers.get(0).getBtg().getBuyTogetherLimitTime()*60*60*1000-new Date().getTime();
        Long endTime=startTime.getTime()+buyTogetherUsers.get(0).getBtg().getBuyTogetherLimitTime()*60*60*1000;
        Integer leftNum=buyTogetherUsers.get(0).getBtg().getNeedTogetherNum()-y;
        Map data=new HashMap();
        data.put("userDataList",maps);
        data.put("leftTime", leftTime);
        data.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime));
        data.put("goodsName",buyTogetherUsers.get(0).getBtg().getGoods().getGoodsName());
        data.put("buyTogetherTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(buyTogetherTime));
        data.put("leftNum",leftNum);
        data.put("goodsId",buyTogetherUsers.get(0).getBtg().getGoods().getId());
        return JsonResp.ok(data);
    }



    /**
     * @拼团失败
     * @param userId  令牌
     * @param  buyTogetherCode 拼团号
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/buyTogetherFail", method = RequestMethod.GET)
    public JsonResp buyTogetherFail(Long userId,String buyTogetherCode){
        log.debug("拼团失败");
        Map map=new HashMap();
        map.put("buyTogetherCode",buyTogetherCode);
        map.put("status",3);
        map.put("isActivityOn",0);
        List<BuyTogetherUser> buyTogetherUsers = buyTogetherUserService.selectBuyTogetherUser(map);
        List<Map> maps=new ArrayList<>();
        Long skuId=null;
        int i=0,y=buyTogetherUsers.size();
        for(;i<y;i++){
            Map map1=new HashMap();
            BuyTogetherUser buyTogetherUser=buyTogetherUsers.get(i);
            if(userId.equals(buyTogetherUser.getMuserId())){
                skuId=buyTogetherUser.getSkuId();
            }
            map1.put("avatarUrl",buyTogetherUser.getMuser().getAvatarUrl());
            map1.put("isHead",buyTogetherUser.getHead());
            map1.put("buyTogetherTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(buyTogetherUser.getBuyTogetherTime()));
            map1.put("buyTogetherCode",buyTogetherUser.getBuyTogetherCode());
            map1.put("userName",buyTogetherUser.getMuser().getUserName());
            maps.add(map1);
        }
        Map data=new HashMap();
        data.put("userDataList",maps);
        Sku sku=skuService.selectById(skuId);
        data.put("propStr",sku.getPropStr());
        data.put("buyTogetherPrice",buyTogetherUsers.get(0).getBtg().getBuyTogetherPrice());
        data.put("goods",buyTogetherUsers.get(0).getBtg().getGoods());
        data.put("needTogetherNum",buyTogetherUsers.get(0).getBtg().getNeedTogetherNum());
        return JsonResp.ok(data);
    }

}
